package info.pinlab.pinplayer.view.swing;


import info.pinlab.pinplayer.model.response.Response;
import info.pinlab.pinplayer.model.response.ResponseContent;
import info.pinlab.pinplayer.model.response.ResponseContentText;

import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextField;

@SuppressWarnings("serial")
public class EntryTaskPanel extends AbstractTaskPanel{
	private final JTextField txtField ;
	private final JButton btn;
	private final JPanel respPanel; 
	
	public EntryTaskPanel(){
		super();
		
		respPanel = new JPanel(new GridBagLayout());
		GridBagConstraints gbc = GbcFactory.getRow();
		gbc.gridx = 0;
		gbc.ipady = 0;
		gbc.ipadx = 10;
		
		txtField = new JTextField();
		respPanel.add(txtField, gbc);
		Font origFont = txtField.getFont();
		txtField.setFont(origFont.deriveFont(24.0F));
		
		btn = new JButton("Send");
		gbc.gridx = 1;
		gbc.ipady = 18;
		gbc.fill = GridBagConstraints.NONE;
		gbc.weightx = 0.0;
		respPanel.add(btn, gbc);

		btn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e){
				final String usrTxt = EntryTaskPanel.this.txtField.getText();
				long rt = e.getWhen() - EntryTaskPanel.this.displayT;
				if (EntryTaskPanel.this.taskController != null){
					EntryTaskPanel.this.taskController.enrollResponse(new ResponseContentText(e.getWhen(), rt, usrTxt));
				}
			}
		});
		super.setBottomPanel(respPanel);
		new Thread(new Runnable() {
			@Override
			public void run() {
//				try {
//					Thread.sleep(1000);
//				} catch (InterruptedException e) {
//					 TODO Auto-generated catch block
//					e.printStackTrace();
//				}
				txtField.requestFocusInWindow();
//				txtField.requestFocus();
			}
		}).start();
		
		super.setDefaultFocus(txtField);
	}

	

	@Override
	public ResponseContent getResponse() {
		long t1 = System.currentTimeMillis();
		return new ResponseContentText(super.displayT-t1, t1, txtField.getText());
	}

	
	@Override
	public void setState(Response response) {
		ResponseContent content = response.getContent();
		if(content instanceof ResponseContentText){
			String usrTxt = ((ResponseContentText)content).getText();
			txtField.setText(usrTxt);
			
		}
	}




}
